package com.example.pceb.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pceb.VO.RegistrationAuditVO;
import com.example.pceb.entity.RegistrationAudit;
import com.example.pceb.entity.User;
import com.example.pceb.entity.SchoolAdmin;
import com.example.pceb.entity.Enterprise;
import com.example.pceb.mapper.RegistrationAuditMapper;
import com.example.pceb.mapper.UserMapper;
import com.example.pceb.mapper.SchoolAdminMapper;
import com.example.pceb.mapper.EnterpriseMapper;
import com.example.pceb.result.Result;
import com.example.pceb.result.ResultCode;
import com.example.pceb.service.RegistrationAuditService;
import com.example.pceb.service.UserService;
import com.example.pceb.VO.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class RegistrationAuditServiceImpl implements RegistrationAuditService {

    @Autowired
    private RegistrationAuditMapper registrationAuditMapper;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private SchoolAdminMapper schoolAdminMapper;
    
    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Override
    public Result<String> submitAudit(RegistrationAuditVO auditVO) {
        try {
            // 检查用户名是否已存在
            QueryWrapper<RegistrationAudit> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", auditVO.getUsername());
            if (registrationAuditMapper.selectOne(queryWrapper) != null) {
                return Result.fail("该用户名已有审核申请，请勿重复提交", ResultCode.FAIL);
            }
            
            // 创建审核记录
            RegistrationAudit audit = new RegistrationAudit();
            audit.setUsername(auditVO.getUsername());
            audit.setPassword(auditVO.getPassword());
            audit.setIdentity(auditVO.getIdentity());
            audit.setPhone(auditVO.getPhone());
            audit.setEmail(auditVO.getEmail());
            audit.setRealName(auditVO.getRealName());
            audit.setOrganization(auditVO.getOrganization());
            audit.setPosition(auditVO.getPosition());
            audit.setIdCard(auditVO.getIdCard());
            audit.setBusinessLicense(auditVO.getBusinessLicense());
            audit.setSchoolCode(auditVO.getSchoolCode());
            audit.setIdCardImage(auditVO.getIdCardImage());
            audit.setBusinessLicenseImage(auditVO.getBusinessLicenseImage());
            audit.setAuthorizationLetter(auditVO.getAuthorizationLetter());
            audit.setStatus(0); // 待审核
            audit.setCreateTime(new Date());
            audit.setUpdateTime(new Date());
            
            int result = registrationAuditMapper.insert(audit);
            if (result > 0) {
                return Result.success("审核申请提交成功，请等待管理员审核");
            } else {
                return Result.fail("审核申请提交失败", ResultCode.FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("提交审核申请时发生错误: " + e.getMessage(), ResultCode.FAIL);
        }
    }

    @Override
    public Result<String> auditRegistration(Long auditId, Integer status, String remark, String auditor) {
        try {
            RegistrationAudit audit = registrationAuditMapper.selectById(auditId);
            if (audit == null) {
                return Result.fail("审核记录不存在", ResultCode.FAIL);
            }
            
            if (audit.getStatus() != 0) {
                String statusText = audit.getStatus() == 1 ? "已通过" : "已拒绝";
                return Result.fail("该申请已被审核（状态：" + statusText + "）", ResultCode.FAIL);
            }
            
            // 更新审核状态
            audit.setStatus(status);
            audit.setAuditRemark(remark);
            audit.setAuditor(auditor);
            audit.setAuditTime(new Date());
            audit.setUpdateTime(new Date());
            
            int result = registrationAuditMapper.updateById(audit);
            if (result > 0) {
                // 如果审核通过（status == 1），创建用户账号
                if (status == 1) {
                    Result<String> createUserResult = createUserFromAudit(audit);
                    if (createUserResult.getCode() != 200) {
                        return Result.fail("审核通过但创建用户账号失败: " + createUserResult.getMessage(), ResultCode.FAIL);
                    }
                }
                
                return Result.success("审核操作成功");
            } else {
                return Result.fail("审核操作失败", ResultCode.FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("审核操作时发生错误: " + e.getMessage(), ResultCode.FAIL);
        }
    }

    @Override
    public Result<Object> getPendingAudits() {
        try {
            QueryWrapper<RegistrationAudit> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 0);
            queryWrapper.orderByDesc("create_time");
            
            List<RegistrationAudit> audits = registrationAuditMapper.selectList(queryWrapper);
            return Result.success(audits);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("获取待审核列表失败: " + e.getMessage(), ResultCode.FAIL);
        }
    }

    @Override
    public Result<Object> getAuditHistory() {
        try {
            QueryWrapper<RegistrationAudit> queryWrapper = new QueryWrapper<>();
            queryWrapper.ne("status", 0);
            queryWrapper.orderByDesc("audit_time");
            
            List<RegistrationAudit> audits = registrationAuditMapper.selectList(queryWrapper);
            return Result.success(audits);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("获取审核历史失败: " + e.getMessage(), ResultCode.FAIL);
        }
    }

    @Override
    public Result<Object> getAllAudits() {
        try {
            QueryWrapper<RegistrationAudit> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_time");
            
            List<RegistrationAudit> audits = registrationAuditMapper.selectList(queryWrapper);
            return Result.success(audits);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("获取所有审核记录失败: " + e.getMessage(), ResultCode.FAIL);
        }
    }

    /**
     * 根据审核记录创建用户账号
     */
    private Result<String> createUserFromAudit(RegistrationAudit audit) {
        try {
            // 1. 创建用户基础信息
            User user = new User();
            user.setUsername(audit.getUsername());
            user.setPassword(audit.getPassword());
            user.setIdentity(audit.getIdentity());
            user.setPhone(audit.getPhone());
            user.setEmail(audit.getEmail());
            
            int userInsert = userMapper.insert(user);
            if (userInsert != 1) {
                return Result.fail("User表插入失败", ResultCode.FAIL);
            }

            // 2. 根据身份类型创建对应的详细信息
            switch (audit.getIdentity()) {
                case "1": // 学校管理员
                    SchoolAdmin schoolAdmin = new SchoolAdmin();
                    schoolAdmin.setUsername(audit.getUsername());
                    schoolAdmin.setName(audit.getRealName());
                    schoolAdmin.setSchoolId(1); // 默认学校ID，可以根据需要调整
                    schoolAdmin.setPhone(audit.getPhone());
                    schoolAdmin.setEmail(audit.getEmail());
                    schoolAdminMapper.insert(schoolAdmin);
                    break;
                    
                case "2": // 企业管理员
                    Enterprise enterprise = new Enterprise();
                    enterprise.setUsername(audit.getUsername());
                    enterprise.setEnterprise(audit.getOrganization());
                    enterprise.setPhone(audit.getPhone());
                    enterprise.setEmail(audit.getEmail());
                    enterprise.setType("企业管理员");
                    enterprise.setTime(new Date());
                    enterpriseMapper.insert(enterprise);
                    break;
                    
                default:
                    return Result.fail("无效的用户身份类型", ResultCode.FAIL);
            }

            return Result.success("用户账号创建成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("创建用户账号时发生错误: " + e.getMessage(), ResultCode.FAIL);
        }
    }
} 